package cn.topcodes.tcsf.wechat.listener;

import cn.topcode.unicorn.wxsdk.WXMessageListener;
import cn.topcodes.tcsf.wechat.domain.entity.WechatPushLog;
import cn.topcodes.tcsf.wechat.event.TemplateSendFinishEvent;
import cn.topcodes.tcsf.wechat.service.WechatPushLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Objects;

@Component
@Lazy(false)
public class TemplateMessageResultListener extends WXMessageListener<TemplateSendFinishEvent> {

    @Autowired
    private WechatPushLogService wechatPushLogService;

    @Override
    public void onReceive(TemplateSendFinishEvent templateSendFinishEvent) {
        long msgId = Long.parseLong(templateSendFinishEvent.getMsgId());
        Example example = wechatPushLogService.buildExample();
        example.or().andEqualTo(WechatPushLog.FIELD_MSG_ID, msgId);
        WechatPushLog pushLog = this.wechatPushLogService.findOne(example);
        if (pushLog != null) {
            if (Objects.equals(templateSendFinishEvent.getStatus(), TemplateSendFinishEvent.STATUS_SUCCESS)) {
                pushLog.setState(WechatPushLog.TYPE_TRUE);
            } else {
                pushLog.setState(WechatPushLog.TYPE_FALSE);
                pushLog.setReason(templateSendFinishEvent.getStatus());
            }
            wechatPushLogService.save(pushLog);
        }
    }
}
